var yaGrid=new Class({
    Implements:Options,
    options:{
        ignoreClass:'header',
        checkAll:'effectAll',
        checkboxFilter:'input[name=\'id[]\']',
        style:{
            hover:'rowHover',
            checked:'rowChecked'
        }
    },
    initialize:function(dataSource,options){
        this.rows=$(dataSource).getElements('tbody tr[class!='+this.options.ignoreClass+']');
        if (this.rows.length==0) return;
        if(options) this.setOptions(options);
        this.rows.each(function(row){
            row.addEvents({
                'mouseover':function(){
                    if(!row.hasClass(this.options.style.checked)){
                        row.addClass(this.options.style.hover);
                    }
                    if(this.options.rowMouseover){
                        this.options.rowMouseover.run(this,row);
                    }
                }.bind(this),
                'mouseout':function(){
                    if(!row.hasClass(this.options.style.checked)){
                        row.removeClass(this.options.style.hover);
                    }
                    if(this.options.rowMouseout){
                        this.options.rowMouseout.run(this,row);
                    }
                }.bind(this),
                'click':function(){
                    this.toggleRowChecked(row);
                }.bind(this)
            });
            //checkbox filter
            var ips=row.getElement(this.options.checkboxFilter);
            if(ips){
                row.store('cb',ips);
                if(true==ips.getProperty('checked')){
                    row.addClass(this.options.style.rowChecked);
                }else{
                    row.removeClass(this.options.style.rowChecked);
                }
                ips.addEvent('click',function(event){
                    ips.setProperty('checked',(ips.getProperty('checked'))?false:true);
                });
            }
        },this);
        //select/disselect all
        var effectAll=$(this.options.checkAll);
        if(effectAll){
            effectAll.addEvent('click',function(){
                this.toggleAllRowsChecked(effectAll);
            }.bind(this));
        }
    },
    toggleRowChecked:function(row){
        var cb=row.retrieve('cb');
        if( !cb) return;
        if(cb.getProperty('checked')){
            this.unCheckRow(row,cb);
        }else{
            this.checkRow(row,cb);
        }
    },
    unCheckRow:function(row,cb){
        cb=cb || row.retrieve('cb');
        cb.setProperty('checked',false);
        row.removeClass(this.options.style.checked);
    },
    checkRow:function(row,cb){
        cb=cb || row.retrieve('cb');
        cb.setProperty('checked',true);
        row.addClass(this.options.style.checked);
    },
    toggleAllRowsChecked:function(effectAll){
        if(effectAll.getProperty('checked')){
            this.rows.each(function(row){
                this.checkRow(row);
            },this);
        }else{
            this.rows.each(function(row){
                this.unCheckRow(row);
            },this);
        }
    },
    getChecked:function(){
        var c=0,str=[];
        this.rows.each(function(row){
            var cb=row.retrieve('cb');
            if(cb.getProperty('checked')){
                c++;
                str.push(cb.getProperty('value'));
            }
        });
        return {'count':c,'value':str.join(',')};
    }
});

var app=new Hash();

var yaFormCheck=new Class({
    Implements:Options,
    options:{},
    initialize:function(fm,options){
        if (this.form = $(fm)) {
            this.validEles=[];  //要验证的元素
            this.regexs=$merge({},top.Regexs);      //正则表达式库
            this.tips=$merge({},top.Lang);          //验证失败时的提示消息
            this.form.getElements('input,select,textarea').each(function(el){
                if(this.checkEle(el)){
                    this.validEles.push(el);
                }
            },this);
        }
    },
    checkEle:function(el){
        var classStyle=el.getProperty('class');
        if((pos=classStyle.indexOf('validate['))>=0){
            var rule=classStyle.substring(pos+9,classStyle.indexOf(']',pos));
            el.store('validate_required',rule.indexOf('equired')>=0);
            el.store('rules',rule.split(','));
            el.addEvents({
                'blur':function(){
                    this.doValidate(el);
                }.bind(this)
            });
            return true;
        }
        return false;
    },
    checkAll:function(){
        var pass = true;
        this.validEles.each(function(el){
            if(!this.doValidate(el)){
                pass = false;
            }
        },this);
        return pass;
    },
    submitByAjax:function(params){
        var opts=$merge({
                    onRequest:function(){ top.showMsg(top.Lang['js_ajax_saveing']); },
                    onFailure:function(){ top.showMsg(top.Lang['js_ajax_failure']);}
                },params);
        this.form.set('send',{
            url:this.form.getProperty('action'),
            method:'post',
            onRequest:opts.onRequest,
            onFailure:opts.onFailure,
            onSuccess:function(txt){
                var json = JSON.decode(txt);
                if(opts.onSuccess) opts.onSuccess(json);
                else{
                    var msg=(json.status) ? (opts.successMsg || json.info || top.Lang['js_base_operate_success']) : (opts.failMsg || json.info || top.Lang['js_base_operate_fail']);
                    top.showMsg(msg,{type:json.status,disappear:1,onDisappear:function(){
                        top.fixedMsg(json.status,msg);
                        if(opts.callback){ opts.callback(json.status,json); }
                    }});
                }
            }
        });
        this.form.send();
    },
    doValidate:function(el){
        this.cleanError(el);
        var val=this.getValue(el);
        var errs=[];
        if(!el.retrieve('validate_required') && val.length==0){
            return true;
        }
        el.retrieve('rules').each(function(rule){
            if(this.regexs[rule] && ! val.test(this.regexs[rule])){
                errs.push(this.tips['js_validate_'+rule]);
            }
        },this);
        if(errs.length==0) return true;
        this.showError(el,errs);
        return false;
    },
    showError:function(el,errs){
        var div=el.getPrevious('.vatip:first-child');
        if(!div){
            div=new Element('div',{'class':'vatip clearfix','styles':{'display':'none'}});
            div.inject(el,'before');
        }
        div.empty();
        var ul=new Element('ul');
        div.grab(ul);
        errs.each(function(err){
            ul.grab(new Element('li',{'html':err}));
        });
        div.setStyle('display','block');
    },
    cleanError:function(el){
        var div=el.getPrevious('.vatip:first-child');
        if(div){
            div.setStyle('display','none');
        }
    },
    getValue:function(el){
        if(el.get('tag')=='select'){
            var selected=el.getSelected();
            if(selected.length==1){
                return (selected[0].value).trim();
            }else if(selected.length>1){
                //todo
            }
        }else{
            return (el.getProperty('value')).trim();
        }
    }
});

//标准提交方式检测..@todo 待改进
function act(operate,params){
    var opts = $merge({'grid':'gridInst','form':'mainForm'},params);
    var fm = document.forms[opts.form];
    if(!fm.elements['a'].value) fm.elements['a'].value = operate;
    if(operate=='edit' || operate=='removal'){
        if(app.has(opts.grid)){
            checkedInfo=(app.get(opts.grid)).getChecked();
            if(checkedInfo.count==0){
                alert(top.Lang['js_base_pls_select_record']);
                return;
            }
        }
        if(operate=='edit'){
        	var arrs=checkedInfo.value.split(',');
            window.location=fm.getAttribute('action')+'&a='+operate+'&id='+arrs[0];
        }else{
            fm.submit();
        }
    }else if(operate=='back'){
        top.pageBack();
    }else if(operate=='save' || operate=='update'){
        //表单检测
        var formCheck = app.get( fm.getProperty('id'));
        if(!formCheck.checkAll()) return;
        formCheck.submitByAjax({
            callback:function(){
                if(params.callback){
                    params.callback();
                }else{
                    top.pageBack();
                }
            }
        });
    }
}

function bindInputEff(ips){
	ips.setProperties({
        'autocomplete':'off'
    });
	ips.addClass('textInput');
	ips.addEvents({
        'focus':function(){
            this.removeClass('textInput').addClass('textInputFocus');
        },
        'blur':function(){
            this.removeClass('textInputFocus').addClass('textInput');
        }
    });	
}

$(window).addEvents({
    'domready':function(){
        top.title(document.title);
        //为输入型控件附加效果
        var ips=$$('input[type=text]','input[type=password]','textarea');
        ips.each(function(ele){ bindInputEff(ele); });
        //创建数据网格
        $$('table.data').each(function(grid,gridIndex){
            var idstr=(grid.id) ? grid.id : '__g_'+gridIndex;
            var gridOpt={};
            if(typeof _gridOptions !='undefined'){
                gridOpt=_gridOptions;
            }
            app.set(idstr,new yaGrid(grid,gridOpt));
        });
        //事件回调
        if(typeof onDomready =='function'){
            onDomready();
        }
        if(typeof searchOpts !== 'undefined'){
            top.registerSearch(searchOpts);
        }
        top.addURLHistory(window.location.href);//保存历史记录
        
        $$('.validateform').each(function(fm){
            app.set(fm.getProperty('id'),new yaFormCheck(fm));
        });
    }
});

/**
 * tools
 */
function setSelectOption(selectEle,val){
    var opt=$(selectEle).getElement('option[value='+val+']');
    if(opt){
        opt.selected=true;
    }
}

/**
 * 高亮关键字
 * words:要高亮的关键字(多个关键字则以数组形式传入)
 * opts.selector:DOM选择器，即在哪个范围内搜索关键词
 * opts.nodeName:胜于包裹关键词的元素名称，默认为span
 * opts.className：上条所指元素的class，默认为highlight
 *
 */
function highlight(words,options){
    if($type(words)=='string'){
        words=[words];
    }
    var opts=options || {};
    var flag=opts.caseSensitive ? '' : 'i';
    var pattern='('+words.join('|')+')';
    if(opts.wordsOnly){
        pattern='\\b'+pattern+'\\b';
    }
    var re=new RegExp(pattern,flag);
    $(window).addEvent('domready',function(){
        $$( opts.selector || document.body ).each(function(node){
            _highlight(node,re,opts.nodeName || 'span',opts.className || 'highlight');
        });
    });
}
function _highlight(node,re,nodeName,className){
    if(node.nodeType===3){
        var match=node.data.match(re);
        if(match){
            var hl=new Element(nodeName,{'class':className});
            var wordNode=node.splitText(match.index);
            wordNode.splitText(match[0].length);
            hl.appendChild(wordNode.cloneNode(true));
            wordNode.parentNode.replaceChild(hl,wordNode);
            return 1;
        }
    }else if(node.nodeType===1 && node.childNodes && !/(script|style)/i.test(node.tagName) && ! ( node.tagName===nodeName.toUpperCase() &&node.className === className )){
        var nodes=node.childNodes;
        for(var i=0,len=nodes.length;i<len;i++){
            i+=_highlight(nodes[i],re,nodeName,className);
        }
    }
    return 0;
}